/*
 * Copyright (c) 2017. danlu.com Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.dlware.net.func;

import com.danlu.lib.net.exception.ServerProtocolException;
import com.danlu.lib.net.exception.TokenInvalidException;

import cn.com.dhc.danlu.dlware.net.ProtocolConstant;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.freedom.response.base.BaseResponseWrapper;
import rx.functions.Func1;

/**
 * author: wuhaiyang(<a href="mailto:wuhaiyang@danlu.com">wuhaiyang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-02-06 下午2:02<br/>
 *
 * <p>
 * 拦截服务器返回的公共数据，判断里面的状态码
 * </p>
 */
public class ServerProtocolFunc <T extends BaseResponse> implements Func1<BaseResponseWrapper<T>, T> {

    @Override
    public T call(BaseResponseWrapper<T> tResultBean) {
        int code = tResultBean.getCode();
        if (code == ProtocolConstant.SUCCESS) {
            return tResultBean.getModel();
        } else if (code == ProtocolConstant.INVALIDTOKEN || code == ProtocolConstant.INVALIDSESSION) {
            throw new TokenInvalidException();
        } else if (code == ProtocolConstant.ERRORROLE) {
            throw new ServerProtocolException(code, "无权限");
        } else if (code == ProtocolConstant.BADREQUESTS) {
            throw new ServerProtocolException(code, "非法请求参数");
        } else if (code == ProtocolConstant.SERVERERROR) {
            throw new ServerProtocolException(code, "服务器异常");
        }
        return tResultBean.getModel();
    }
}
